import Taro from '@tarojs/taro'
import { useDispatch } from 'react-redux'
import { Button } from '@tarojs/components'
import { AtModal, AtModalAction, AtModalContent, AtModalHeader } from 'taro-ui'

import * as api from 'src/api'
import { getUserInfo } from 'src/store/slice/user'

import './index.scss'

export default ({ visible, onClose }) => {
  const dispatch = useDispatch()

  const bindPhone = async (e) => {
    try {
      await api.userBindPhone(e.detail)
      dispatch(getUserInfo())
      onClose()
    } catch (error) {
      Taro.showToast({
        title: error,
        icon: 'none',
      })
    }
  }

  return (
    <AtModal className="bind-phone-number" isOpened={visible}>
      <AtModalHeader>授权提醒</AtModalHeader>
      <AtModalContent>请授权手机号码，以便完善您的个人信息</AtModalContent>
      <AtModalAction>
        <Button onClick={onClose}>取消</Button>
        <Button open-type="getPhoneNumber" onGetPhoneNumber={bindPhone}>
          授权
        </Button>
      </AtModalAction>
    </AtModal>
  )
}
